package com.byron.media.server.rtsp;

import com.byron.media.server.rtsp.config.RtspConfig;
import com.byron.media.server.rtsp.handlers.RtspHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.rtsp.RtspDecoder;
import io.netty.handler.codec.rtsp.RtspEncoder;
import io.netty.util.concurrent.Future;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class RtspServer {

    private RtspConfig config;

    private EventLoopGroup bossGroup;

    private EventLoopGroup workerGroup;

    public RtspServer(RtspConfig config, EventLoopGroup bossGroup, EventLoopGroup workerGroup) {
        this.config = config;
        this.bossGroup = bossGroup;
        this.workerGroup = workerGroup;
    }

    public void init(){
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(bossGroup, workerGroup);
        serverBootstrap.childOption(ChannelOption.SO_RCVBUF, 64 * 1024)
                .childOption(ChannelOption.SO_SNDBUF, 64 * 1024)
                .childOption(ChannelOption.WRITE_BUFFER_WATER_MARK, new WriteBufferWaterMark(64 * 1024 / 2, 64 * 1024))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        socketChannel.pipeline()
                                .addLast(new RtspDecoder())
                                .addLast(new RtspEncoder())
//                                    .addLast(new LoggingHandler())
                                .addLast(new HttpObjectAggregator(64 * 1024))
                                .addLast(new RtspHandler());
                    }
                });
        log.warn("Gonsin RTSP Server 配置启动完成");
        try {
            ChannelFuture closeFuture = serverBootstrap.bind(config.getPort()).sync();
            closeFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.warn("Gonsin RTSP Server 关闭");
    }


}
